import { create } from 'domain';
import {createStore,applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import {ClassifyProp} from '../types/classify.d';
import {ListProp,Types} from '../types/list.d';

interface Istate{
    classify:ClassifyProp[],
    list:ListProp[],
    detail:ListProp,
    loveList:ListProp[],
    carList:Types[]
}

let reducer = (state:Istate={classify:[],list:[],carList:[],detail:{
    id:-1,
    pic:'',
    name:'',
    desc:'',
    num:1,
    type:'',
    parent:1,
    comment:[]
},loveList:[]},action:any) => {
    switch (action.type) {
        //初始化分类数据
        case 'initClassify':{
            return {...state,classify:[...action.classify]}
        }
        //根据分类查询菜谱列表
        case 'getList':{
            return {...state,list:[...action.list]}
        }
        //设置详情
        case 'detail':{
            return {...state,detail:{...action.detail}}
        }
        //修改收藏数据
        case 'addLove':{
            //收藏的对象  id
            let index = state.loveList.findIndex(item => item.id == action.target.id);
            if(index == -1){
                //没有收藏
                state.detail.num++;
                state.loveList = [...state.loveList,action.target];
            }else{
                //收藏
                state.detail.num--;
                state.loveList.splice(index,1);
            }
            return {...state,detail:{...state.detail},loveList:[...state.loveList]}
        }
        //添加评论
        case 'addComment':{
            state.detail.comment = [...state.detail.comment,action.comment];
            return {...state}
        }

        case 'getCarList':{
            console.log(action)
            return {...state,carList:[...action.carlist]}
        }
        case 'changeNum':{
            let index = state.carList[action.parentIndex].children.findIndex(item => item.id === action.productId);
            if(action.status === '+'){
                state.carList[action.parentIndex].children[index].num++;
                state.carList[action.parentIndex].num++;
            }else{
                if(state.carList[action.parentIndex].children[index].num > 0){
                    state.carList[action.parentIndex].children[index].num--;
                }else{
                    state.carList[action.parentIndex].children.splice(index,1);
                }
                state.carList[action.parentIndex].num--;
            }
            
            state.carList[action.parentIndex] = {...state.carList[action.parentIndex]};
            return {...state,carList:[...state.carList]}
        }
        default:
            return state;
    }
}

let store = createStore(reducer,applyMiddleware(thunk));

export default store